package com.jzy.gulimall.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzy.common.constant.ProductConstant;
import com.jzy.common.to.SkuHasStockRespVo;
import com.jzy.common.to.SkuReductionTo;
import com.jzy.common.to.SpuBoundTo;
import com.jzy.common.to.es.SkuEsTo;
import com.jzy.common.utils.PageUtils;
import com.jzy.common.utils.Query;
import com.jzy.common.utils.R;
import com.jzy.gulimall.product.dao.SpuInfoDao;
import com.jzy.gulimall.product.entity.*;
import com.jzy.gulimall.product.exception.RRException;
import com.jzy.gulimall.product.feign.CouponFeignService;
import com.jzy.gulimall.product.feign.SearchFeignService;
import com.jzy.gulimall.product.feign.WareFeignService;
import com.jzy.gulimall.product.service.*;
import com.jzy.gulimall.product.vo.sku.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    private SpuInfoDescService spuInfoDescService;

    @Resource
    private SpuImagesService spuImagesService;

    @Resource
    private AttrService attrService;

    @Resource
    private ProductAttrValueService productAttrValueService;

    @Resource
    private SkuInfoService skuInfoService;

    @Resource
    private SkuImagesService skuImagesService;

    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Resource
    private CouponFeignService couponFeignService;

    @Resource
    private BrandService brandService;

    @Resource
    private CategoryService categoryService;

    @Resource
    private WareFeignService wareFeignService;

    @Resource
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 发布商品 保存
     */
    // TODO: 2020/9/8 分布式事务 失败处理 回滚处理 服务降级
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1.保存spu基本信息   pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtil.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);
        //2.保存spu的描述信息  pms_spu_info_desc
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setDecript(String.join(",", vo.getDecript()));
        descEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescService.saveSpuInfoDesc(descEntity);
        //3.保存spu的图片集   pms_spu_images
        spuImagesService.saveImages(spuInfoEntity.getId(), vo.getImages());
        //4.保存spu的规格参数  pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            valueEntity.setSpuId(spuInfoEntity.getId());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            AttrEntity byId = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(byId.getAttrName());
            return valueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(collect);
        //保存spu积分信息  sms_spu_bounds
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtil.copyProperties(vo.getBounds(), spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu分信息失败");
        }
        //5.保存sku信息
        //5.1 sku基本信息   pms_sku_info
        List<Skus> skus = vo.getSkus();
        if (CollectionUtil.isNotEmpty(skus)) {
            skus.forEach(item -> {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtil.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                List<Images> defaultImage = item.getImages().stream()
                        .filter(img -> img.getDefaultImg() == 1).collect(Collectors.toList());
                skuInfoEntity.setSkuDefaultImg(defaultImage.get(0).getImgUrl());
                skuInfoService.saveSkuInfo(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId();
                //5.2 sku图片信息   pms_sku_images
                List<SkuImagesEntity> images = item.getImages().stream().filter(entity -> StringUtils.isNotBlank(entity.getImgUrl())).map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).collect(Collectors.toList());
                // 2020/9/8 没有图片路径的无需保存
                skuImagesService.saveBatch(images);
                //5.3 sku销售属性值  pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuAttrList = attr.stream().map(skuAttr -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtil.copyProperties(skuAttr, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);
                    return attrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuAttrList);
                //6.sku的优惠,满减信息 gulimall_sms
                // sms_sku_ladder  打折
                // sms_sku_full_reduction 满减
                // sms_member_price 会员
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtil.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                //会员没有判断!
                if (skuReductionTo.getFullCount() > 0
                        || skuReductionTo.getFullPrice().compareTo(new BigDecimal(0)) > 0) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程保存spu优惠信息失败");
                    }
                }
            });
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.save(spuInfoEntity);
    }

    /**
     * spu管理 列表
     * status=0&key=华为&brandId=3&catelogId=225&page=1&limit=10
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String status = (String) params.get("status");
        if (StringUtils.isNotBlank(status)) {
            wrapper.eq("publish_status", status);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            wrapper.and(wrap -> wrap.eq("id", key).or().like("spu_name", key));
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotBlank(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotBlank(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    /**
     * spu管理 上架
     * product/spuinfo/3/up
     */
    @Override
    public void spuUp(Long spuId) {
        //组装es数据
        //1.查询spu对应的sku信息
        List<SkuInfoEntity> skuList = skuInfoService.getSkusBySpuId(spuId);
        if (CollectionUtil.isEmpty(skuList)) {
            throw new RRException("没有对应商品信息");
        }

        //2.查询spu所有的 可以被检索的规格属性
        List<ProductAttrValueEntity> baseAttr = productAttrValueService.baseAttrlistforspu(spuId);
        //查出pms_product_attr_value中所有spu的规格属性 id
        List<Long> attrIds = baseAttr.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        //从pms_attr中筛选 可检索的attrId
        List<Long> attrSearchIds = attrService.selectSearchAttrIds(attrIds);
        HashSet<Long> idSet = new HashSet<>(attrSearchIds);
        //封装每个sku信息的attrs
        List<SkuEsTo.Attrs> attrsList = baseAttr.stream().filter(item -> idSet.contains(item.getAttrId())).map(item -> {
            SkuEsTo.Attrs attrs = new SkuEsTo.Attrs();
            BeanUtil.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());

        //远程调用 查询库存系统是否有库存
        List<Long> skuIds = skuList.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> skuHasStockResult = null;
        try {
            R skuHasStock = wareFeignService.getSkuHasStock(skuIds);
            TypeReference<List<SkuHasStockRespVo>> typeReference = new TypeReference<List<SkuHasStockRespVo>>() {
            }; //返回指定的类型
            skuHasStockResult = skuHasStock.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockRespVo::getSkuId, SkuHasStockRespVo::getHasStock));
        } catch (Exception e) {
            log.error("库存服务查询异常,原因:{}", e);
        }

        //3.封装每个sku信息
        Map<Long, Boolean> finalSkuHasStockResult = skuHasStockResult;
        List<SkuEsTo> skuEsTos = skuList.stream().map(sku -> {
            SkuEsTo skuEsTo = new SkuEsTo();
            BeanUtil.copyProperties(sku, skuEsTo);
            skuEsTo.setSkuPrice(sku.getPrice());
            skuEsTo.setSkuImg(sku.getSkuDefaultImg());
            //是否有库存
            if (null == finalSkuHasStockResult) {
                skuEsTo.setHasStock(true);
            } else {
                skuEsTo.setHasStock(finalSkuHasStockResult.get(sku.getSkuId()));
            }
            // TODO: 2020/9/11  热度评分 默认放0
            skuEsTo.setHotScore(0L);
            //查询品牌和分类名
            BrandEntity brand = brandService.getById(sku.getBrandId());
            skuEsTo.setBrandName(brand.getName());
            skuEsTo.setBrandImg(brand.getLogo());
            CategoryEntity category = categoryService.getById(sku.getCatalogId());
            skuEsTo.setCatalogName(category.getName());
            skuEsTo.setAttrs(attrsList);
            return skuEsTo;
        }).collect(Collectors.toList());

        //发给es进行保存
        R r = searchFeignService.productStateUp(skuEsTos);
        if (r.getCode() == 0) {
            //修改spu更新时间
            //修改spu上架状态
            SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
            spuInfoEntity.setId(spuId);
            spuInfoEntity.setPublishStatus(ProductConstant.SpuStatusEnum.SPU_UP.getCode());
            spuInfoEntity.setUpdateTime(new Date());
            baseMapper.updateById(spuInfoEntity);
        } else {
            //远程调用失败
            /**
             * feign调用流程
             * 1.构造请求数据,将对象转为json  构造一个requestTemplate
             * 2.发送请求进行执行   执行成功会解码响应数据
             * 3.请求失败会重试 直到一定次数 默认关闭状态
             */
            // TODO: 2020/9/12  重复调用问题 接口幂等性
        }

    }

    /**
     * 提交订单  生成订单
     * 远程调用 根据skuId获取spu信息
     */
    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        return baseMapper.selectById(byId.getSpuId());
    }

}